// 获取主入口文件
const fs = require('fs')
const parser = require('@babel/parser')
const traverse = require('@babel/traverse').default
const path = require('path')
const babel = require('@babel/core')


const getModuleInfo = (file) => {
  const body = fs.readFileSync(file, 'utf-8')
  const ast = parser.parse(body, {
    sourceType: 'module'   //解析es模块
  })

  const deps = {}

  traverse(ast, {
    ImportDeclaration({ node }) {
      const dirname = path.dirname(file)
      const adspath = './' + path.join(dirname, node.source.value)
      deps[node.source.value] = adspath
    }
  })

  // console.log(deps);

  const { code } = babel.transformFromAst(ast, null, { presets: ['@babel/preset-env'] })

  const moduleInfo = { file, deps, code }

  return moduleInfo
}

// 递归获取依赖
const parseModules = (file) => {
  const entry = getModuleInfo(file)
  const temp = [entry]
  for (let i = 0; i < temp.length; i++) {
    const deps = temp[i].deps
    if (deps) {
      for (let key in deps) {
        if (deps.hasOwnProperty(key)) {
          temp.push(getModuleInfo(deps[key]))
        }
      }
    }
  }
  let depsGraph = {}
  temp.forEach(moduleInfo => {
    depsGraph[moduleInfo.file] = {
      deps: moduleInfo.deps,
      code: moduleInfo.code
    }
  })
  return depsGraph
}

// 处理require、export关键字
const bundle = (file) => {
  const depsGraph = JSON.stringify(parseModules(file))
  return `(function (graph) {
    function require(file) {
        function absRequire(relPath) {
            return require(graph[file].deps[relPath])
        }
        var exports = {};
        (function (require,exports,code) {
            eval(code)
        })(absRequire,exports,graph[file].code)
        return exports
    }
    require('${file}')
})(${depsGraph})`

}

const content = bundle('./src/index.js')
fs.mkdirSync('./dist')
fs.writeFileSync('./dist/index.js',content)
// fs.writeFileSync(file)
// console.log(content);